package com.xxx.car.component;

import com.alibaba.fastjson.JSON;
import com.xxx.car.cache.CarRedisTemplate;
import com.xxx.car.constants.CarConstants;
import com.xxx.car.entity.vo.AppUserCacheInfo;
import com.xxx.car.redisCluster.utils.JsonUtil;
import com.xxx.common.base.enums.ApiResponseEnum;
import com.xxx.common.base.vo.APIResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;


/**
 * Created by youxiaojia on 2017/6/16.
 */
@Component
public class CommonFilter implements Filter {

    private static final Logger logger = LoggerFactory.getLogger(CommonFilter.class);

    @Autowired
    private CarRedisTemplate carRedisTemplate;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void destroy() {
    }

    private void ajaxError(ApiResponseEnum apiResponseEnum, HttpServletResponse response)
            throws IOException {
        response.setHeader("Content-Type","application/json");
        response.getWriter().write(JSON.toJSON(APIResponse.returnFail(apiResponseEnum)).toString());
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        String uri = request.getRequestURI();
//        String sign = request.getHeader(CarConstants.USER_SIGN);

        ServletRequest requestWrapper = new HttpServletRequestWrapper(request);
//        String reqData = getBodyString(requestWrapper.getReader(), uri);

        if(uri.startsWith("/api")) {

//            if (reqData == null) {
//                ajaxError(ApiResponseEnum.BODY_IS_NULL, response);
//                return;
//            }
//            if(sign == null){
//                ajaxError(ApiResponseEnum.SIGN_IS_NULL, response);
//                return;
//            }
//            String md5Sign = MD5Utils.MD5Encode(reqData + CarConstants.SECRET_KEY);
//            if (!sign.equals(md5Sign)) {
//                logger.info("-----------签名不一致，客户端签名:{}，服务器签名:{}" ,sign,md5Sign);
//                ajaxError(ApiResponseEnum.ILLEGAL_PROTOCOL, response);
//                return;
//            }
            try{
                String uMsg = request.getHeader(CarConstants.USER_INFORMATION_MARK);
                Integer userId = null ;
                Object redisUsg = carRedisTemplate.get(uMsg);
                if (redisUsg == null){
                    ajaxError(ApiResponseEnum.COOKIES_IS_NULL, response);
                    return;
                }
                AppUserCacheInfo appUserCacheInfo =(AppUserCacheInfo) JsonUtil.parseJsonStr2Object(redisUsg.toString(),AppUserCacheInfo.class);
                if (appUserCacheInfo != null) {
                    userId = appUserCacheInfo.getUid();
                    if (userId != null) {
                        request.setAttribute("userId", userId); //userId不为null表示已经登录, 为null表示为游客身份
                        request.setAttribute(CarConstants.USER_INFORMATION_MARK,uMsg);
                    }
                    else {
                        request.setAttribute("userId", userId);
                        request.setAttribute(CarConstants.USER_INFORMATION_MARK,uMsg);

                    }
                    chain.doFilter(requestWrapper, response);
                }
                else {
                    ajaxError(ApiResponseEnum.NEED_USER_LOGIN, response);
                    return;
                }
                logger.info("================= userCookiesName:{} ==> uid:{} =================", uMsg,userId);
            }catch (Exception e){
                e.printStackTrace();
                chain.doFilter(requestWrapper, response);
            }
        } else {
            chain.doFilter(requestWrapper, response);
        }
        //logger.warn("Request End，Request URI: " + request.getRequestURI()+ "，Time spent: " + (System.currentTimeMillis() - startTime) + "ms");
    }


    public static String getBodyString(BufferedReader br, String reqUrl) {
        String inputLine;
        String str = "";
        try {
            while ((inputLine = br.readLine()) != null) {
                str += inputLine;
            }
            br.close();
        } catch (IOException e) {
            logger.warn("requestUrl: " + reqUrl + ", Request error: "
                    + e.getMessage() + "Request URI: ");

        }
        return str;
    }

}
